import UIKit
import JRNetworkSpeedInclude

class JRNetworkSpeedHelper: NSObject {
    class func getInterfaceBytes() -> JRNetworkSpeedModel! {
        var ifa_list : UnsafeMutablePointer<ifaddrs>?
        if getifaddrs(&ifa_list) == -1 { return nil }
        guard let firstAddr = ifa_list else { return nil }
        var iBytes: UInt32 = 0
        var oBytes: UInt32 = 0
        let seq = sequence(first: firstAddr, next: { $0.pointee.ifa_next })
        for ifa in seq {
            let ifaPointee = ifa.pointee
            let addr = ifaPointee.ifa_addr.pointee
            if addr.sa_family != UInt8(AF_LINK) { continue }
            let ifaflags = Int32(ifaPointee.ifa_flags)
            if (ifaflags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) != (IFF_UP|IFF_RUNNING) { continue }
            let ifadata = ifaPointee.ifa_data
            if ifadata == nil { continue }
            if strncmp(ifaPointee.ifa_name, "lo", 2) != 0 {
                let if_datax = ifadata!.assumingMemoryBound(to: if_data.self)
                iBytes += if_datax.pointee.ifi_ibytes
                oBytes += if_datax.pointee.ifi_obytes
            }
        }
        freeifaddrs(ifa_list)
        return JRNetworkSpeedModel.init(oValue: oBytes, iValue: iBytes)
    }
}
